<template>
  <a-drawer
    title="修改区域"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="areaEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form">
      <a-form-item label='区域名称' v-bind="formItemLayout">
        <a-input v-decorator="['areaName',
                   {rules: [
                    { required: true, message: '区域名称不能为空'},
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='区域排序' v-bind="formItemLayout">
        <a-input-number v-decorator="['orderNum']" style="width: 100%"/>
      </a-form-item>
      <a-form-item label='区域管理员' v-bind="formItemLayout">
        <a-input-search v-decorator="['resident',
                   {rules: [
                    { required: true, message: '区域管理员不能为空'},
                    { max: 20, message: '请选择'}
                  ]}]"
                  enter-button="搜索"
                  @search="showRsSearch">
        </a-input-search>
      </a-form-item>
      <a-form-item label='上级区域'
                   style="margin-bottom: 2rem"
                   v-bind="formItemLayout">
        <a-tree
          ref="areaTree"
          :key="areaTreeKey"
          :checkable="true"
          :checkStrictly="true"
          @check="handleCheck"
          @expand="handleExpand"
          :expandedKeys="expandedKeys"
          :defaultCheckedKeys="defaultCheckedKeys"
          :treeData="areaTreeData">
        </a-tree>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="2" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
    <!-- 查询用户 -->
    <rs-search
      @close="handleRsSearchClose"
      @success="handleRsSearchSuccess"
      :searchType="'区域管理员'"
      :ownerVisible="rsSearch.rsVisible">
    </rs-search>
  </a-drawer>
</template>
<script>
import RsSearch from '../shop/RsSearch'

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'AreaEdit',
  props: {
      areaEditVisiable: {
      default: false
    }
  },
  components: {RsSearch},
  data () {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      areaTreeKey: +new Date(),
      tArea: {},
      checkedKeys: [],
      checkedLevelNums: [],
      expandedKeys: [],
      areaTreeData: [],
      defaultCheckedKeys: [],
      rsSearch: {
        rsVisible: false,
        rsId: ''
      }
    }
  },
  methods: {
    reset () {
      this.loading = false
      this.areaTreeKey = +new Date()
      this.expandedKeys = this.checkedKeys = this.defaultCheckedKeys = []
      this.tArea = {}
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleCheck (checkedKeys, info) {
      this.checkedKeys = checkedKeys
      info.checkedNodes.forEach(cn => {
          this.checkedLevelNums.push(cn.data.props.value)
      })
    },
    expandAll () {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll () {
      this.expandedKeys = []
    },
    handleExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    setFormValues ({...tArea}) {
      this.form.getFieldDecorator('areaName')
      this.form.setFieldsValue({'areaName': tArea.text})
      this.form.getFieldDecorator('orderNum')
      this.form.setFieldsValue({'orderNum': tArea.order})
      this.form.getFieldDecorator('resident')
      this.form.setFieldsValue({'resident': tArea.residents[0].rsName})
      this.rsSearch.rsId = tArea.residents[0].id
      if (tArea.parentId !== '0') {
        this.defaultCheckedKeys.push(tArea.parentId)
        this.checkedKeys = this.defaultCheckedKeys
        this.expandedKeys = this.checkedKeys
      }
      this.tArea.areaId = tArea.id
      this.tArea.levelNum = tArea.value
      this.areaTreeKey = +new Date()
    },
    handleSubmit () {
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked
      if (checkedArr.length > 1) {
        this.$message.error('最多只能选择一个上级区域，请修改')
        return
      }
      if (checkedArr[0] === this.tArea.areaId) {
        this.$message.error('不能选择自己作为上级区域，请修改')
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          let tArea = this.form.getFieldsValue()
          tArea.areaId = this.tArea.areaId
          if (checkedArr.length) {
              tArea.parentId = checkedArr[0]
              tArea.levelNum = (parseInt(this.checkedLevelNums[0]) + 1).toString()
          } else {
              tArea.parentId = ''
              tArea.levelNum = '1'
          }
          tArea.residents = [{id: this.rsSearch.rsId}]
          this.$put('tArea', {
            ...tArea
          }).then(() => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    handleRsSearchClose () {
      this.rsSearch.rsVisible = false
    },
    handleRsSearchSuccess (rs, searchType) {
      this.rsSearch.rsVisible = false
      if (searchType === '区域管理员') {
        this.form.setFieldsValue({
          resident: rs.rsName || rs.cardId
        })
        this.rsSearch.rsId = rs.id || ''
      } else if (searchType === 'opter') {
        this.form.setFieldsValue({
          opeName: rs.rsName || rs.cardId
        })
        this.rsSearch.opeId = rs.id || ''
      }
    },
    showRsSearch () {
      this.rsSearch.rsVisible = true
    }
  },
  watch: {
    areaEditVisiable () {
      if (this.areaEditVisiable) {
        this.$get('tArea', {

        }).then((r) => {
          this.areaTreeData = r.data.rows.children
          this.allTreeKeys = r.data.ids
          this.areaTreeKey = +new Date()
        })
      }
    }
  }
}
</script>
